<?php


namespace app\event;


use think\event;
use think\facade\Db;
use think\facade\Log as Logger;

class SqlEvent extends event
{
	public function handle()
	{
		// 事件处理逻辑
		/*Db::listen(function($sql, $runtime, $master) {
			// 记录SQL
			echo $sql . ' [' . $runtime . 's] ' . ($master ? 'master' : 'slave');
			// 查看性能分析结果
			//dump($explain);
		});*/
		
		// think\dbConnection ->trigger
		Db::listen(function($sql, $runtime, $master) {
			if (0 === strpos($sql, 'CONNECT:')) {
				Logger::write($sql, 'connect');
				return;
			}
			
			// 记录SQL
			if (is_bool($master)) {
				// 分布式记录当前操作的主从
				$master = $master ? 'master|' : 'slave|';
			} else {
				$master = '';
			}
			
			Logger::write($sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]', 'connect');
		});
	}
}